package org.example.config.advice;

import org.apache.commons.collections4.CollectionUtils;
import org.example.base.entity.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 响应方法返回值处理类
 *
 * @author Zjy
 * @since 2022-05-06
 */
@Component
@RestControllerAdvice
public class ApiResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !Objects.requireNonNull(returnType.getMethod()).getReturnType().isAssignableFrom(Void.TYPE);
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> httpMessageConverter, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        List<String> list = serverHttpRequest.getHeaders().get("traceId");
        // 统一响应体
        Result<?> apiResult;
        if (methodParameter.getParameterType().isAssignableFrom(Result.class)) {
            apiResult = (Result<?>) body;
        } else {
            apiResult = Result.OK(body);
        }
        if (Objects.nonNull(apiResult) && CollectionUtils.isNotEmpty(list)) {
            apiResult.setTraceId(list.get(0));
        }
        return apiResult;
    }

}
